# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2022/7/16
import math
import os
from time import sleep

import requests
from submodules.common.lib.log_ import get_logger

from submodules.common.lib.json_ import json_file_to_dict, dict_to_json_file

from submodules.common.lib import local_paths

from submodules.common.lib.datetime_ import get_timestamp

from lib.ts_ import get_code_list_tx, get_stock_list

logger = get_logger()


def get_market_info_all(stock_list):
    """
    https://qt.gtimg.cn/q=sz000001
    :return:
    0: 未知
    1: 名字
    2: 代码
    3: 当前价格
    4: 昨收
    5: 今开
    6: 成交量（手）
    7: 外盘
    8: 内盘
    9: 买一
    10: 买一量（手）
    11-18: 买二 买五
    19: 卖一
    20: 卖一量
    21-28: 卖二 卖五
    29: 最近逐笔成交
    30: 时间
    31: 涨跌
    32: 涨跌%
    33: 最高
    34: 最低
    35: 价格/成交量（手）/成交额
    36: 成交量（手）
    37: 成交额（万）
    38: 换手率
    39: 市盈率
    40:
    41: 最高
    42: 最低
    43: 振幅
    44: 流通市值
    45: 总市值
    46: 市净率
    47: 涨停价
    48: 跌停价
    """

    name = "market_info_all"

    data_dir = os.path.join(local_paths.project_tmp_path, "data")
    if os.path.exists(data_dir):
        pass
    else:
        os.mkdir(data_dir)
    date_str = get_timestamp()[:8]
    data_path = os.path.join(data_dir, f"{date_str}_{name}.json")
    if os.path.exists(data_path):
        try:
            res = json_file_to_dict(data_path)
            logger.info(f"use local data, data_name:{name}")
            return res
        except Exception as e:
            logger.error(f"data_path:{data_path}")
            logger.error(repr(e))

    url = "https://qt.gtimg.cn/"

    ts_code_list_tx = get_code_list_tx(stock_list)
    market_info_all_tx = {}

    step = 500  # 1000不可用 500可用
    for i in range(math.ceil(len(stock_list) / step)):
        start = i * step
        end = (i + 1) * step
        ts_code_list_tx_tmp = ts_code_list_tx[start:end]
        headers = {}
        params = {"q": ",".join(ts_code_list_tx_tmp)}
        for i in range(300):
            try:
                res = requests.get(
                    url=url, headers=headers, params=params, verify=False
                )
                break
            except Exception as e:
                logger.error(repr(e))
                sleep(1)
        res = res.text.split(";")
        for i2 in range(len(res) - 1):
            tmp_list = res[i2].strip().replace(" ", "").split("~")
            if tmp_list[44] == "":
                # 流通市值
                tmp_list[44] = 0
            market_info_all_tx.update({ts_code_list_tx_tmp[i2]: tmp_list})

    dict_to_json_file(market_info_all_tx, data_path)
    return market_info_all_tx


def get_code_list_tx_pre_screen(market_info_all):
    """
    市盈率
    流通市值
    市净率
    :param market_info_all:
    :return:
    """

    市盈率1 = 0
    市盈率2 = 20
    流通市值1 = 10
    流通市值2 = 500
    市净率1 = 0
    市净率2 = 15
    code_list_tx = []
    for code, content in market_info_all.items():
        市盈率 = float(content[39])
        流通市值 = float(content[44])
        市净率 = float(content[46])
        if 市盈率 < 市盈率1 or 市盈率 > 市盈率2:
            continue
        if 流通市值 < 流通市值1 or 流通市值 > 流通市值2:
            continue
        if 市净率 < 市净率1 or 市净率 > 市净率2:
            continue
        code_list_tx.append(code)
    return code_list_tx


def get_candles_data(tx_code):
    """
    http://data.gtimg.cn/flashdata/hushen/daily/13/sz000858.js

    :param tx_code:
    :return:
    """

    headers = {}
    params = {}

    year_str = get_timestamp()[2:4]

    url = f"http://data.gtimg.cn/flashdata/hushen/daily/{year_str}/{tx_code}.js"
    candles_data = []
    for i in range(300):
        try:
            res = requests.get(url=url, headers=headers, params=params, verify=False)
            break
        except:
            sleep(1)
    list_tmp = res.text.split("\\n\\")[1:-1]

    for i in range(len(list_tmp)):
        data = list_tmp[i].strip("\n").split(" ")

        trade_date = data[0]
        open = float(data[1])
        high = float(data[3])
        low = float(data[4])
        close = float(data[2])
        vol = data[5]
        amount = 0
        gains_percent = (close / open - 1) * 100  # 涨幅 index=7
        amplitude_percent = (high / low - 1) * 100  # 振幅 index=8

        candles_data.append(
            [
                trade_date,
                open,
                high,
                low,
                close,
                vol,
                amount,
                gains_percent,
                amplitude_percent,
            ]
        )
    return candles_data


if __name__ == "__main__":

    def test_get_market_info_all():
        stock_list = get_stock_list()
        res = get_market_info_all(stock_list)
        print(res)
        print(len(res))

    def test_get_code_tx_pre_screen():
        stock_list = get_stock_list()
        market_info_all = get_market_info_all(stock_list)
        res = get_code_list_tx_pre_screen(market_info_all)
        print(res)
        print(len(res))

    def test_get_candles_data():
        tx_code = "sz000858"
        res = get_candles_data(tx_code)
        print(res)

    test_get_market_info_all()
